/*
 * Adara WebCam TimeLapse capture software.
 * Copyright (C) 2012 AdaraProjectTeam
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

package adara.core;

import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.apache.log4j.Logger;

import com.lti.civil.CaptureException;
import com.lti.civil.CaptureObserver;
import com.lti.civil.CaptureStream;
import com.lti.civil.Image;
import com.lti.civil.awt.AWTImageConverter;

/**
 * This class implements the functionality of getting the images from attached
 * device and save them to provided directory.
 * @author Andrei Ermicioi (aka erani) <andrei.ermicioi@gmail.com>
 *
 */
public class Process implements Runnable {
	
	private static final Logger logger = Logger.getLogger(Process.class);

	private Device device;
	private int timegap;
	private File storage;
	private CaptureStream stream;
	
	private boolean isAlive;
//	private Collection<IPlugin> plugins;
	
	Process(Device device, int timegap, File storage, CaptureStream stream) {
		this.device = device;
		this.timegap = timegap;
		this.storage = storage;
		this.stream = stream;
		
//		this.plugins = PluginManager.getPlugins();
		
		this.stream.setObserver(new CaptureObserver() {
			
			long nextTime = -1;
			
			@Override
			public void onNewImage(CaptureStream stream, Image image) {
				long imgTimestamp = image.getTimestamp() / 1000;
				
				if (nextTime == -1) {
					nextTime = imgTimestamp + Process.this.timegap;
					
					if (logger.isTraceEnabled())
						logger.trace("Next snapshot at: " + nextTime);
					
					return;
				}
				
				if (nextTime > imgTimestamp) {
					return;
				}
				
				File fimage = new File(Process.this.storage.getAbsolutePath() 
						+ File.separator + nextTime + ".png");
				
				try {
					ImageIO.write(AWTImageConverter.toBufferedImage(image),
							"png", fimage);
				} catch (IOException e) {
					throw new CoreRuntimeException(
							"Could not save images to storage directory", e);
				}
				
//				for (IPlugin plugin : Process.this.plugins) {
//					plugin.onNewImage(null);
//				}
				
				nextTime += Process.this.timegap;
				
				if (logger.isTraceEnabled())
					logger.trace("Next snapshot at: " + nextTime);
			}
			
			@Override
			public void onError(CaptureStream stream, CaptureException e) {
				throw new CoreRuntimeException(e);
			}
		});
	}
	
	@Override
	public void run() {
		if (device.isLocked()) {
			throw new CoreRuntimeException("Device is locked");
		}
		
		synchronized (device) {
			if (device.isLocked()) {
				throw new CoreRuntimeException("Device is locked");
			}
			
			if (logger.isTraceEnabled()) {
				logger.trace("Locking device");
			}
			
			device.lock();
		}
		
		try {
			if (logger.isTraceEnabled())
				logger.trace("Starting stream");
			
			stream.start();
		} catch (CaptureException e) {
			throw new CoreRuntimeException(e);
		}
		
		while (isAlive) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) { }
		}
		
		try {
			if (logger.isTraceEnabled())
				logger.trace("Stoping stream");
			
			stream.stop();
		} catch (CaptureException e) {
			throw new CoreRuntimeException(e);
		}
		
		try {
			if (logger.isTraceEnabled())
				logger.trace("Disposing stream");
			
			stream.dispose();
		} catch (CaptureException e) {
			throw new CoreRuntimeException(e);
		}
		
		if (logger.isTraceEnabled()) 
			logger.trace("Device unlocked");
		
		device.unlock();
		
	}
	
	public void start() {
		isAlive = true;
		new Thread(this).start();
	}
	
	public void stop() {
		isAlive = false;
	}
}
